//
//  SGSEventsViewController.m
//  AgileNYC
//
//  Created by German on 29.07.14.
//  Copyright (c) 2014 Softlegion. All rights reserved.
//

#import "SGSAppDelegate.h"
#import "SGSEventsViewController.h"
#import "SGSEventViewCell.h"
#import "SGSEventGroupViewCell.h"
#import "GSEventSocialViewCell.h"
#import "GSTableSection.h"
#import "GSEvent.h"
#import "SGSModelsManager.h"
#import "SGSEventDescriptionViewController.h"
#import "SGSUtils.h"
#import "SGSDialogsManager.h"
#import "GSMenuViewController.h"
#import "SGSDelegatesManager.h"
#import "SGSProfileROViewController.h"
#import "SGSAppConsts.h"

static BOOL menuIsVisible;

@interface SGSEventsViewController ()

@property (weak, nonatomic) SGSEventViewCell * currentSelectedCell;

@property (strong, nonatomic) NSArray * sectionsArray;
@property (strong, nonatomic) NSString * currentSearchString;

@end

@implementation SGSEventsViewController


- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onStartRenewEvents)
                                                 name:eventsWillRenewNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onEndRenewEvents)
                                                 name:eventsDidRenewNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onErrorRenewEvents)
                                                 name:eventsDidNotRenewNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onEndUpdateEvents)
                                                 name:eventsDidUpdateNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onProfileUpdate)
                                                 name:profileDidUpdateNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(scheduleShow)
                                                 name:menuScheduleButtonClickNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(contactsShow)
                                                 name:menuContactsButtonClickNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(myProfileShow)
                                                 name:menuMyProfileButtonClickNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(helpShow)
                                                 name:menuHelpButtonClickNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(aboutShow)
                                                 name:menuAboutButtonClickNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(settingsShow)
                                                 name:menuSettingsButtonClickNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(hideMenu)
                                                 name:menuCloseButtonClickNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onPushNotification:)
                                                 name:receivedRemoteNotification
                                               object:nil];
    
    SGSModelsManager * modelsManager =  [SGSModelsManager sharedModelsManager];
    [modelsManager arrayOfContacts];
    
    SGSDelegatesManager * delegatesManager = [SGSDelegatesManager sharedDelegatesManager];
    delegatesManager.currentEventsVC = self;
    
    menuIsVisible = NO;
    self.currentSearchString = nil;
    
    [self loadSessionID];
    
    self.sectionsArray = [self generateSections:modelsManager.arrayOfEvents];
    [self.pnlEventsListTable reloadData];
    
    UISwipeGestureRecognizer * swipeLeftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleLeftSwipe:)];
    UISwipeGestureRecognizer * swipeRightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleRightSwipe:)];
    
    swipeLeftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    swipeRightRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    
    [self.view addGestureRecognizer:swipeLeftRecognizer];
    [self.view addGestureRecognizer:swipeRightRecognizer];
    
    [self hideMenu];
    
    GSLog(GSLogEvent, @"----- SGSEventsViewController Did Load");
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    SGSDelegatesManager * delegatesManager = [SGSDelegatesManager sharedDelegatesManager];
    
    if (modelsManager.isFirstRun) {
        modelsManager.isFirstRun = NO;
        UIViewController * vc = delegatesManager.currentHelpVC;
        //[self.navigationController pushViewController:vc animated:NO];
        [self presentViewController:vc animated:YES completion:nil];
    } else if (delegatesManager.controllerToBeOpened) {
        UIViewController * vc = delegatesManager.controllerToBeOpened;
        delegatesManager.controllerToBeOpened = nil;
        
        [self.navigationController pushViewController:vc animated:NO];
    }
    
    GSEvent * currEvent = [SGSModelsManager sharedModelsManager].currentEvent;
    
    if ((self.currentSelectedCell) && (currEvent)) {
        
        self.currentSelectedCell.imgCheckIn.hidden = ![currEvent.isCheckIn boolValue];
        
    }
    
    // Check did we load the events
    [self checkEventsLoaded];
    
    GSLog(GSLogEvent, @"----- SGSEventsViewController Did Appear");
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    GSLog(GSLogEvent, @"----- SGSEventsViewController Will Disappear");
}


-(NSArray*) generateSections:(NSArray*) arrayOfEvents  {
    NSMutableArray * sectionsArray = [NSMutableArray array];
    
    NSString * currentCaption = nil;
    GSTableSection * section = nil;
    
    for (GSEvent * event in arrayOfEvents) {
        
        if ((self.currentSearchString) && ([self.currentSearchString length]>0) && ([[event allEventData] rangeOfString:self.currentSearchString].location==NSNotFound)) {
            continue;
        }

        NSString * caption = [event eventDateInString];
        
        if (![currentCaption isEqualToString:caption]) {
            section = [[GSTableSection alloc] init];
            section.sectionName = caption;
            section.items = [NSMutableArray array];
            currentCaption = caption;
            [sectionsArray addObject:section];
            [sectionsArray addObject:event];
        } else {
            //section = [sectionsArray lastObject];
            [sectionsArray addObject:event];
        }

        //[section.items addObject:event];
    }
    
    return sectionsArray;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    [self hideMenu];
    
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];

    if (cell.tag==0) return;
    
    self.currentSelectedCell = (SGSEventViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    
    [[SGSModelsManager sharedModelsManager] makeEventCurrentByID:[NSNumber numberWithInteger:self.currentSelectedCell.tag]];
    
    GSLog(GSLogInfo, @"[SGSEventsViewController] didSelectRowAtIndexPath: Selected event: %@", [SGSModelsManager sharedModelsManager].currentEvent.topic);
    
    SGSEventDescriptionViewController * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"SGSEventDescriptionViewController"];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    id itemInArray = [self.sectionsArray objectAtIndex:indexPath.row];
    
    if ([itemInArray isKindOfClass:[GSEvent class]]) {
        GSEvent * event = (GSEvent*) itemInArray;
        CGFloat curHeight = [tableView rowHeight];
        
        if ([event.author length]==0) {
            curHeight = [tableView rowHeight]/2.03;
        }
        
        return curHeight;
        
    } else {
        return [tableView rowHeight]/5.13;
    }
  
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //NSInteger sectionsCount = [self.sectionsArray count];
    
    //GSLog(GSLogInfo, @"[GSEventsViewController] numberOfSectionsInTableView: %d",sectionsCount);
    
    //return sectionsCount;
    return 1;
}

#if !USE_GROUPED_EVENTS
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString * sectionTitle = [[self.sectionsArray objectAtIndex:section] sectionName];
    
    //GSLog(GSLogInfo, @"[GSEventsViewController] titleForHeaderInSection: %@ forSection: %d",sectionTitle, section);
    
    return sectionTitle;
}
#endif


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    /*GSTableSection * sec = [self.sectionsArray objectAtIndex:section];
    
    NSInteger rowsCount = [sec.items count];
    
    return rowsCount;*/
    
    return [self.sectionsArray count];
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id itemInArray = [self.sectionsArray objectAtIndex:indexPath.row];
    

    NSString * cellIdentifier;

    UITableViewCell * resultCell;
    
    
    if ([itemInArray isKindOfClass:[GSEvent class]])
    {
        GSEvent * curEvent = (GSEvent*) itemInArray;
        
        if ((curEvent.author) && ([curEvent.author length]>0)) {
        
            cellIdentifier = @"EventCell";
           
            SGSEventViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            
            if (!cell) {
                cell = [[SGSEventViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            
            [cell.spinnerPhoto startAnimating];
            cell.lbEventTitle.textAlignment = NSTextAlignmentLeft;
            cell.lbEventTitle.lineBreakMode = NSLineBreakByWordWrapping;
            cell.lbEventTitle.text = [[NSString stringWithFormat:@"%@",curEvent.topic] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            cell.lbAuthor.text = [[NSString stringWithFormat:@"%@",curEvent.author] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            cell.lbTime.text = curEvent.eventTimeRangeInString;
            cell.lbTrack.text = curEvent.room;

            cell.imgCheckIn.hidden = ![curEvent.isCheckIn boolValue];
            
            cell.tag = [curEvent.eventId integerValue];
            
            [self alignCaptions:cell];
            
            cell.imgAuthorPhoto.image = [UIImage imageNamed:No_Event_Photo_Name];

            [[SGSModelsManager sharedModelsManager] requestImageForEventByEvent:curEvent onComplete:^(BOOL result, UIImage *image) {
                cell.imgAuthorPhoto.image = image;
                [cell.spinnerPhoto stopAnimating];
            }];
            
            resultCell = cell;
        } else {
            cellIdentifier = @"EventSocialCell";
            
            GSEventSocialViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            
            if (!cell) {
                cell = [[GSEventSocialViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            
            cell.lbEventTitle.textAlignment = NSTextAlignmentLeft;
            cell.lbEventTitle.lineBreakMode = NSLineBreakByWordWrapping;
            
            cell.lbEventTitle.text = [[NSString stringWithFormat:@"%@",curEvent.topic] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            
            cell.lbTime.text = curEvent.eventTimeRangeInString;
            cell.lbTrack.text = curEvent.room;
            
            cell.imgCheckIn.hidden = ![curEvent.isCheckIn boolValue];
            
            if ([curEvent.introduction length]==0) {
                cell.tag = 0;
                cell.imgNarrow.hidden = YES;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            } else {
                cell.tag = [curEvent.eventId integerValue];
                cell.imgNarrow.hidden = NO;
                cell.selectionStyle = UITableViewCellSelectionStyleDefault;
            }
            
            [self alignCaptions:cell];
            
            resultCell = cell;
        }
            
    } else {
        cellIdentifier = @"EventGroupCell";
        
        SGSEventGroupViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        if (!cell) {
            cell = [[SGSEventGroupViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        
        GSTableSection * section = [self.sectionsArray objectAtIndex:indexPath.row];
        
        cell.labEventDay.text = section.sectionName;
        cell.tag = 0;

        resultCell = cell;
    }

    
    return resultCell;
}

#pragma mark - Menu Operations

-(void) changeMenuPosition:(CGFloat) position toFront:(id) object {
    
    __weak __typeof(self) weakSelf = self;
    
    [UIView animateWithDuration:0.4f
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         __strong typeof(self)self = weakSelf;

                         self.pnlMenuList.frame = CGRectMake(position,
                                                             self.pnlMenuList.frame.origin.y,
                                                             self.pnlMenuList.frame.size.width,
                                                             self.pnlMenuList.frame.size.height);
                     }
                     completion:^(BOOL finished){
                         //__strong typeof(self)self = weakSelf;
                         
                         //[self.view bringSubviewToFront:object];
                     }];
}

-(void) hideMenu {
    if (menuIsVisible) {
        [self changeMenuPosition:self.pnlMenuList.frame.size.width*-1 toFront:self.pnlEventsListTable];
        menuIsVisible = !(menuIsVisible);
        
    }
}

-(void) showMenu {
    if (!menuIsVisible) {
        [self.view bringSubviewToFront:self.pnlMenuList];
        [self changeMenuPosition:0 toFront:self.pnlMenuList];
        menuIsVisible = !(menuIsVisible);
    }
}

#pragma mark - Connection Dialog

-(void) showConnectionDialog {
    [self checkLoginAndMakeConnection];
}

-(void) showConnectionRequestDialog:(NSString*) requesterName
                        requesterID:(NSInteger) requesterID {
    
    [[SGSDialogsManager dialogsManager]
     showRequestDialog:requesterName
     onComplete:^(NSInteger buttonIndex) {
         
         GSLog(GSLogInfo, @"[SGSEventsViewController] Connection request dialog. Button pressed: %d", buttonIndex);
         
         BOOL reply = NO;
         BOOL needToShowProfile = NO;
         
         switch (buttonIndex) {
             case 0: //Accept
                 GSLog(GSLogInfo, @"[SGSEventsViewController] Connection acepted");
                 reply = YES;
                 needToShowProfile = NO;
                 break;
             case 1: //Ignore
                 GSLog(GSLogWarning, @"[SGSEventsViewController] Connection declined");
                 reply = NO;
                 needToShowProfile = NO;
                 break;
             case 2: //View profile
                 GSLog(GSLogWarning, @"[SGSEventsViewController] Connection info showed");
                 needToShowProfile = YES;
                 break;
             default: GSLog(GSLogWarning, @"[SGSEventsViewController] Unknown button pressed");
         }
         
         if (needToShowProfile) {
             SGSProfileROViewController * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"SGSProfileROViewController"];
             vc.isRequestProfile = YES;
             [self.navigationController pushViewController:vc animated:YES];
         } else {
             [self replyConnectionRequest:reply];
         }
     }];
}

-(void) checkConnectionRequest {
    
    SGSModelsManager * modelsManager =  [SGSModelsManager sharedModelsManager];
    
    [modelsManager checkConnectionRequest:^(BOOL result) {
        if (result) {
            
            [self showConnectionRequestDialog:modelsManager.currentRequester.fullName
                                  requesterID:[modelsManager.currentRequester.sessionID integerValue]];
            
        } else {
            
            
            
        }
        
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    }];
}

-(void) replyConnectionRequest:(BOOL) answer {
    
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    
    [modelsManager replyForConnectionRequest:modelsManager.currentRequester.sessionID
     answer:answer
     onComplete:^(BOOL result) {
         //if (result) {
             [self checkConnectionRequest];
         //}
     }];
}


#pragma mark - Actions and Notifications

- (IBAction)btnMenuShow:(id)sender {
    if (menuIsVisible) {
        [self hideMenu];
    } else {
        [self showMenu];
    }
}

- (IBAction)btnConnectShow:(id)sender {
	[self hideMenu];
	[self showConnectionDialog];
}

-(IBAction) onPushNotification:(NSNotification*)notification {
    
    if (!notification) {
        [self checkConnectionRequest];
        return;
    }

    NSDictionary * userInfo = [notification  userInfo];
    
    if (!userInfo) {
        [self checkConnectionRequest];
        return;
    }
    
    NSDictionary * notificationDict = [userInfo objectForKey:@"aps"];
    
    if (!notificationDict) {
        [self checkConnectionRequest];
        return;
    }
    
    NSString * alertString = [notificationDict objectForKey:@"alert"];
    
    NSRange range = [alertString rangeOfString:@"request" options:NSCaseInsensitiveSearch];
    
    if (range.location==NSNotFound) {
        [self checkConnectionRequest];
    } else {
        [[SGSDialogsManager dialogsManager] showSimpleDialog:Info_Dialog_Title message:alertString onComplete:nil];
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        [[SGSModelsManager sharedModelsManager] replyForReplyForConnectionRequest];
    }
}

-(void) scheduleShow {
    [self hideMenu];
}

-(void) contactsShow {
    [self hideMenu];
    
    [self checkLoginAndOpenController:@"SGSContactsViewController"];
}

-(void) myProfileShow {
    [self hideMenu];
    
    [self checkLoginAndOpenController:@"SGSProfileViewController"];
}

-(void) helpShow {
    [self hideMenu];
    
    UIViewController * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"SGSHelpViewController"];
    
    [self presentViewController:vc animated:YES completion:nil];
}

-(void) aboutShow {
    [self hideMenu];
    
    UIViewController * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"SGSAboutViewController"];
    
    [self.navigationController pushViewController:vc animated:YES];
}

-(void) settingsShow {
    [self hideMenu];
}

-(void) onStartRenewEvents {
    //[self startSpinner];
    GSLog(GSLogInfo, @"[SGSEventsViewController] Notification \"%@\" received", eventsWillRenewNotification);
}

-(void) onEndRenewEvents {
    [self updateEventsTable];
}

-(void) onEndUpdateEvents {
    [self updateEventsTable];
}

-(void) onErrorRenewEvents {
    
}

-(void) onProfileUpdate {
    [self loadSessionID];
    [self checkEventsLoaded]; // Check did we load the events
}


#pragma mark - Internal functions

-(void) checkLoginAndOpenController:(NSString *) controllerName {
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    
    //modelsManager.controllerToBeOpened = controllerName;
    
    SGSDelegatesManager * delegatesManager = [SGSDelegatesManager sharedDelegatesManager];
    delegatesManager.controllerToBeOpened = [delegatesManager getControllerByName:controllerName];
    
    UIViewController * vc;
    
    if (![modelsManager checkUserLogin]) {
        
        //vc = [self.storyboard instantiateViewControllerWithIdentifier:@"SGSLoginViewController"];
        vc = delegatesManager.currentLoginVC;
        
        GSLog(GSLogInfo, @"[SGSEventsViewController] Switched to %@",@"SGSLoginViewController");
        
    } else {
        GSLog(GSLogInfo, @"[SGSEventsViewController] Switched to %@",controllerName);
        
        vc = delegatesManager.controllerToBeOpened;
        delegatesManager.controllerToBeOpened = nil;
        //GSLog(GSLogInfo, @"[SGSEventsViewController] Switched to %@",modelsManager.controllerToBeOpened);
        
        //vc = [self.storyboard instantiateViewControllerWithIdentifier:modelsManager.controllerToBeOpened];
        //modelsManager.controllerToBeOpened = nil;
        //vc = [delegatesManager c]
    }
    
    [self.navigationController pushViewController:vc animated:YES];
}

-(void) checkLoginAndMakeConnection {
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    
    if (![modelsManager checkUserLogin]) {
        
        UIViewController * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"SGSLoginViewController"];
        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
        [[SGSDialogsManager dialogsManager] showConnectionDialog:@""
             onComplete:^(NSInteger buttonIndex, NSString *returnText) {
                 GSLog(GSLogInfo, @"[SGSEventsViewController] Connection dialog. Button pressed: %d. Returned: %@", buttonIndex, returnText);
                 
                 switch (buttonIndex) {
                     case 0: // Connect or Accept
                         [[SGSModelsManager sharedModelsManager] sendConnectionRequest:returnText onComplete:^(BOOL result, NSError * error) {
                             if (!result) {
                                 GSLog(GSLogError, @"[checkLoginAndMakeConnection] Error: %@",[error domain]);
                                 [[SGSDialogsManager dialogsManager] showSimpleDialog:Error_Dialog_Title message:Unable_To_Send_Request_Message onComplete:nil];
                             } else {
                                 [[SGSDialogsManager dialogsManager] showSimpleDialog:Info_Dialog_Title message:@"Connect Request has been sent" onComplete:nil];
                             }
                         }];
                         break;
                     case 1: //Cancel or Decline
                         GSLog(GSLogWarning, @"[SGSEventsViewController] Connection cancelled");
                         break;
                     default: GSLog(GSLogWarning, @"[SGSEventsViewController] Unknown button pressed");
                 }
                 
             }];
    }
}


-(void) loadSessionID {
    NSString * sessionID = [[SGSModelsManager sharedModelsManager] currentUser].sessionID;
    
    if ((sessionID) && (![sessionID isEqualToString:@"0"]) && (![sessionID isEqualToString:@"(null)"])) {
        self.labSessionId.text = sessionID;
        self.labSessionId.hidden = NO;
    } else {
        self.labSessionId.hidden = YES;
    }
}

-(void) checkEventsLoaded {
    NSInteger eventsInTable = [self.pnlEventsListTable numberOfSections];
    
    if (eventsInTable==0) { //it is possible when we jumped to profile page
        SGSModelsManager * modelsManager =  [SGSModelsManager sharedModelsManager];
        
        self.sectionsArray = [self generateSections:modelsManager.arrayOfEvents];
        [self.pnlEventsListTable reloadData];
    }
}

-(void) updateEventsTable {
    
    SGSModelsManager * modelsManager =  [SGSModelsManager sharedModelsManager];
    self.sectionsArray = [self generateSections:modelsManager.arrayOfEvents];
    [self.pnlEventsListTable reloadData];
    
}

#pragma mark - UIGestureRecognizer

-(void) handleLeftSwipe: (UIGestureRecognizer*) sender {
    [self hideMenu];
}

-(void) handleRightSwipe: (UIGestureRecognizer*) sender {
    [self showMenu];
}

#pragma mark - Align functions

-(void) alignCaptions:(UITableViewCell*) cell {
    CGFloat sizeBetweenLabels = 6.0f;
    CGSize eventTitleLabelSize;
    CGSize authorLabelSize;
    CGSize trackLabelSize;
    CGFloat positionY;
    
    const CGFloat maxTitleLabelHeight = 72;
    //const CGFloat maxTitleLabelWidth = 191;

    const CGFloat maxAuthorLabelHeight = 31;
    //const CGFloat maxAuthorLabelWidth = 173;

    const CGFloat maxTrackLabelHeight = 21;
    //const CGFloat maxTrackLabelWidth = 167;

    SGSEventViewCell * eventCell;
    GSEventSocialViewCell * socialCell;
    
    if ([cell isKindOfClass:[SGSEventViewCell class]]) {
        eventCell = (SGSEventViewCell*) cell;
        
        /*if (cell.tag==28) {
            
        }*/

        if ([[eventCell.lbEventTitle.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
            eventTitleLabelSize = CGSizeMake(0, 0);
        } else {
            eventTitleLabelSize = labelSize(eventCell.lbEventTitle, eventCell.lbEventTitle.frame.size.width, maxTitleLabelHeight);
        }
        
        if ([[eventCell.lbAuthor.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
            authorLabelSize = CGSizeMake(0, 0);
        } else {
            authorLabelSize = labelSize(eventCell.lbAuthor, eventCell.lbAuthor.frame.size.width, maxAuthorLabelHeight);
        }
        
        if ([[eventCell.lbTrack.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
            trackLabelSize = CGSizeMake(0, 0);
        } else {
            trackLabelSize = labelSize(eventCell.lbTrack, eventCell.lbTrack.frame.size.width, maxTrackLabelHeight);
        }
        
        CGFloat heightToBound = eventCell.imgAuthorPhoto.frame.size.height;
        
        // Calculate total height of all labels
        CGFloat totalLabelsHeight = eventTitleLabelSize.height;
        
        if (authorLabelSize.height>0) totalLabelsHeight += sizeBetweenLabels;
        
        totalLabelsHeight += authorLabelSize.height;
        
        if (trackLabelSize.height>0) totalLabelsHeight += sizeBetweenLabels;
        
        totalLabelsHeight += trackLabelSize.height;
        
        // Try to align label and image
        
        if (totalLabelsHeight>heightToBound) { //Выравниваем лейблы относительно материнской панели (помещаем лейблы в центр)

            positionY = ((eventCell.frame.size.height-totalLabelsHeight) / 2);
            
        } else { //Выравниваем лейблы относительно фотографии
            
            //positionY = eventCell.imgAuthorPhoto.frame.origin.y + ((eventCell.imgAuthorPhoto.frame.size.height-totalLabelsHeight) / 2);
            positionY = ((eventCell.frame.size.height-totalLabelsHeight) / 2);
            
        }

        //Сжимаем лейблы
        
        eventCell.lbEventTitle.frame = CGRectMake(eventCell.lbEventTitle.frame.origin.x,
                                                  positionY,
                                                  //eventTitleLabelSize.width,
                                                  eventCell.lbEventTitle.frame.size.width,
                                                  eventTitleLabelSize.height);
        
        positionY += eventTitleLabelSize.height;
        
        if (authorLabelSize.height>0) positionY += sizeBetweenLabels;
        
        eventCell.lbAuthor.frame = CGRectMake(eventCell.lbAuthor.frame.origin.x,
                                              positionY,
                                              //authorLabelSize.width,
                                              eventCell.lbAuthor.frame.size.width,
                                              authorLabelSize.height);
        
        positionY += authorLabelSize.height;
        
        if (trackLabelSize.height>0) positionY += sizeBetweenLabels;
        
        eventCell.lbTrack.frame = CGRectMake(eventCell.lbTrack.frame.origin.x,
                                             positionY,
                                             //trackLabelSize.width,
                                             eventCell.lbTrack.frame.size.width,
                                             trackLabelSize.height);

    } else if ([cell isKindOfClass:[GSEventSocialViewCell class]]) {
        socialCell = (GSEventSocialViewCell*)cell;
        
        if ([[socialCell.lbEventTitle.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
            eventTitleLabelSize = CGSizeMake(0, 0);
        } else {
            eventTitleLabelSize = labelSize(socialCell.lbEventTitle, socialCell.lbEventTitle.frame.size.width, maxTitleLabelHeight);
        }
        
        if ([[socialCell.lbTrack.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
            trackLabelSize = CGSizeMake(0, 0);
        } else {
            trackLabelSize = labelSize(socialCell.lbTrack, socialCell.lbTrack.frame.size.width, maxTrackLabelHeight);
        }
        
        //CGFloat heightToBound = socialCell.imgAuthorPhoto.frame.size.height;
        
        // Calculate total height of all labels
        CGFloat totalLabelsHeight = eventTitleLabelSize.height;
        
        if (trackLabelSize.height>0) totalLabelsHeight += sizeBetweenLabels+6;
        
        totalLabelsHeight += trackLabelSize.height;
        
        // Try to align label and image
        
        positionY = ((socialCell.frame.size.height-totalLabelsHeight) / 2);
            
        //Сжимаем лейблы
        
        socialCell.lbEventTitle.frame = CGRectMake(socialCell.lbEventTitle.frame.origin.x,
                                                  positionY,
                                                  //eventTitleLabelSize.width,
                                                  socialCell.lbEventTitle.frame.size.width,
                                                  eventTitleLabelSize.height);
        
        positionY += eventTitleLabelSize.height;
        
        if (trackLabelSize.height>0) positionY += sizeBetweenLabels;
        
        socialCell.lbTrack.frame = CGRectMake(socialCell.lbTrack.frame.origin.x,
                                             positionY,
                                             //trackLabelSize.width,
                                             socialCell.lbTrack.frame.size.width,
                                             trackLabelSize.height);
        
    }
    
    
    
    
    
    
}

#pragma mark - System Functions

- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];}


@end
